package com.quanthium.controller;

import com.quanthium.DeviceShadow;
import com.quanthium.service.DeviceShadowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/device-shadows")
public class DeviceShadowController {

    @Autowired
    private DeviceShadowService deviceShadowService;

    @GetMapping
    public List<DeviceShadow> getAllDeviceShadows() {
        return deviceShadowService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<DeviceShadow> getDeviceShadowById(@PathVariable String id) {
        Optional<DeviceShadow> deviceShadow = deviceShadowService.findById(id);
        return deviceShadow.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public DeviceShadow createDeviceShadow(@RequestBody DeviceShadow deviceShadow) {
        return deviceShadowService.save(deviceShadow);
    }

    @PutMapping("/{id}")
    public ResponseEntity<DeviceShadow> updateDeviceShadow(@PathVariable String id, @RequestBody DeviceShadow deviceShadowDetails) {
        Optional<DeviceShadow> deviceShadow = deviceShadowService.findById(id);
        if (deviceShadow.isPresent()) {
            DeviceShadow updatedDeviceShadow = deviceShadow.get();
            updatedDeviceShadow.setProductId(deviceShadowDetails.getProductId());
            updatedDeviceShadow.setDeviceId(deviceShadowDetails.getDeviceId());
            updatedDeviceShadow.setState(deviceShadowDetails.getState());
            updatedDeviceShadow.setMetadata(deviceShadowDetails.getMetadata());
            updatedDeviceShadow.setVersion(deviceShadowDetails.getVersion());
            updatedDeviceShadow.setTimestamp(deviceShadowDetails.getTimestamp());
            return ResponseEntity.ok(deviceShadowService.save(updatedDeviceShadow));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDeviceShadow(@PathVariable String id) {
        if (deviceShadowService.findById(id).isPresent()) {
            deviceShadowService.deleteById(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}